# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

# The basic page configuration of the applet 
# will automatically generate the QR code of 
# the scenic spot after the configuration is successful
# applet的基本页面配置

#将自动生成的二维码

#配置成功后的景区
import os
from unittest import expectedFailure
import uuid

from flask import Blueprint
from flask import request
import utils.pgsql.pgcase as pgcase
import utils.pgsql.pgadmin
from utils.wraps import token, urlcost
import utils.message.response as response
import utils.common.initres as initres
import utils.common.log as log
import utils.common.func as func
import json
import requests
import uuid

if initres.COS_TYPE :
    import utils.oss.cos as oss   
else :
    import utils.oss.oss as oss

caseconf_module = Blueprint('base_conf', __name__,
                            url_prefix='/api/v1/caseconf')



@caseconf_module.route('/img/<int:caseId>', methods=['POST'])
@token.login_required
@urlcost.cost_count_wraps
def case_put(caseId):
  
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo['role'] in [1, 2, 3]:
        obj = pgcase.PgCase()
        dic = json.loads(request.data)
        channelappinfor = ""
        data = {}
        if userInfo['operatorId'] == 1:
            data['page'] = 'pages/customCamera/cameras'
            channelappinfor = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxf208c5902a55d25b&secret=ad3a871b6198e2a179409002b3b79c10"
        else:
            data['page'] = 'pages/index/index'
            channelappinfor = "https://#############################################"
        try:
            if(obj.get_orCode(caseId)["orCode"] == ""):
                response3 = requests.get(channelappinfor,
                                         headers={"content-type": "application/xml"})
                access_token = json.loads(response3.text)['access_token']
                data['scene'] = "caseId="+str(caseId) + ",channelId=-1"
                data['check_path'] = True
                data['env_version'] = "release"
                response2 = requests.post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token,
                                          json.dumps(data), headers={"content-type": "application/json"})
                if("errcode" in str(response2.content)):
                    return response.make_response_1000()
                else:
                    filename = initres.UPLOADPATH + str(uuid.uuid1()) + ".png"
                    with open(filename, 'wb') as f:
                        f.write(response2.content)
                    filename = oss.upload_webRes(filename)
                    log.logging.info(filename)
                    dic['orCode'] = filename
            res = obj.modify(dic, "caseId", caseId)
            return response.make_response_success(res)
        except:
            res = obj.modify(dic, "caseId", caseId)
            return response.make_response_success(res)
    else:
        return response.make_response_401()


@caseconf_module.route('/info/<int:caseID>', methods=['GET'])
@token.login_required
@urlcost.cost_count_wraps
def case_get(caseID):

    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo['role'] in [1, 2, 3]:
        obj = pgcase.PgCase()
        return response.make_response_success(obj.get(caseID))
    return response.make_response_3000()
